﻿using AutoMapper;
using MediatR;
using System.Transactions;
using Traceability.App.Apilication.Common;
using Traceability.App.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure.Interfance;

namespace Traceability.App.Apilication.Handler
{
    public class UpdateTraceabilityHandler : IRequestHandler<UpdateTraceabilityCommon, ApiResult<int>>
    {
        private readonly IBaseRespository<TraceabilityModel> traceabilityRepo;
        private readonly IMapper mapper;

        public UpdateTraceabilityHandler(IBaseRespository<TraceabilityModel> traceabilityRepo,IMapper mapper)
        {
            this.traceabilityRepo = traceabilityRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(UpdateTraceabilityCommon request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var trace = traceabilityRepo.GetAll().Where(x => x.Production_Batch == request.Production_Batch).FirstOrDefault();
            if (trace != null)
            {
                res.Code = ApiEnum.Error;
                res.Message = "该生产批次已存在";
                return Task.FromResult(res);
            }
            var info = traceabilityRepo.GetValue(request.Traceability_ID).Result;
            var model=mapper.Map(request,info);
            model.UpdateName = "张三";
            model.UpdateTime = DateTime.Now;
            var r = 0;
            using (TransactionScope tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                r= traceabilityRepo.Update(model).Result;
                tran.Complete();
            }
            if(r>0)
            {
                res.Code = ApiEnum.Success;
                res.Message = "修改成功";
                return Task.FromResult(res);
            }
            else
            {
                res.Code = ApiEnum.Error;
                res.Message = "修改失败";
                return Task.FromResult(res);
            }
        }
    }
}
